package com.strange.mdl.module.mdl.controller.admin.activity;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.auth.DefaultCredentials;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import jakarta.validation.constraints.*;
import jakarta.validation.*;
import jakarta.servlet.http.*;
import java.util.*;
import java.io.IOException;

import com.strange.mdl.framework.common.pojo.PageParam;
import com.strange.mdl.framework.common.pojo.PageResult;
import com.strange.mdl.framework.common.pojo.CommonResult;
import com.strange.mdl.framework.common.util.object.BeanUtils;
import static com.strange.mdl.framework.common.pojo.CommonResult.success;

import com.strange.mdl.framework.excel.core.util.ExcelUtils;

import com.strange.mdl.framework.apilog.core.annotation.ApiAccessLog;
import static com.strange.mdl.framework.apilog.core.enums.OperateTypeEnum.*;

import com.strange.mdl.module.mdl.controller.admin.activity.vo.*;
import com.strange.mdl.module.mdl.dal.dataobject.activity.ActivityDO;
import com.strange.mdl.module.mdl.service.activity.ActivityService;

@Tag(name = "管理后台 - 活动")
@RestController
@RequestMapping("/mdl/activity")
@Validated
public class ActivityController {

    @Resource
    private ActivityService activityService;


    /**
     * todo OSS阿里云测试
     * @throws Exception
     */
    public void albbTest() throws Exception {
        String accessKeyId = "LTAI5tLqGQTHAwK8V9xDmrpg";
        String accessKeySecret = "hS6lcVXBqcPzGCrJbffXb3vyNrScHp";

        // 使用固定 AK/SK 初始化凭证提供器
        DefaultCredentials defaultCredentials = new DefaultCredentials(accessKeyId, accessKeySecret);
        DefaultCredentialProvider credentialProvider = new DefaultCredentialProvider(defaultCredentials);
        ClientConfiguration clientConfig = new ClientConfiguration();
        clientConfig.setSignatureVersion(SignVersion.V4); // 使用 V4 签名算法
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        String endpoint = "oss-cn-shenzhen.aliyuncs.com";
        String bucketName = "scripture";
        String region = "cn-shenzhen";
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();
        try {
            // 4. 列出文件
            System.out.println("4. 列出 Bucket 中的文件：");
            ObjectListing objectListing = ossClient.listObjects(bucketName);
            for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                System.out.println(" - " + objectSummary.getKey() + " (大小 = " + objectSummary.getSize() + ")");
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    @PostMapping("/create")
    @Operation(summary = "创建活动")
    @PreAuthorize("@ss.hasPermission('mdl:activity:create')")
    public CommonResult<Long> createActivity(@Valid @RequestBody ActivitySaveReqVO createReqVO) {
        return success(activityService.createActivity(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新活动")
    @PreAuthorize("@ss.hasPermission('mdl:activity:update')")
    public CommonResult<Boolean> updateActivity(@Valid @RequestBody ActivitySaveReqVO updateReqVO) {
        activityService.updateActivity(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除活动")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('mdl:activity:delete')")
    public CommonResult<Boolean> deleteActivity(@RequestParam("id") Long id) {
        activityService.deleteActivity(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除活动")
                @PreAuthorize("@ss.hasPermission('mdl:activity:delete')")
    public CommonResult<Boolean> deleteActivityList(@RequestParam("ids") List<Long> ids) {
        activityService.deleteActivityListByIds(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得活动")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mdl:activity:query')")
    public CommonResult<ActivityRespVO> getActivity(@RequestParam("id") Long id) {
        ActivityDO activity = activityService.getActivity(id);
        return success(BeanUtils.toBean(activity, ActivityRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得活动分页")
    @PreAuthorize("@ss.hasPermission('mdl:activity:query')")
    public CommonResult<PageResult<ActivityRespVO>> getActivityPage(@Valid ActivityPageReqVO pageReqVO) {
//        try {
//            albbTest();
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
        PageResult<ActivityDO> pageResult = activityService.getActivityPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, ActivityRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出活动 Excel")
    @PreAuthorize("@ss.hasPermission('mdl:activity:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportActivityExcel(@Valid ActivityPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ActivityDO> list = activityService.getActivityPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "活动.xls", "数据", ActivityRespVO.class,
                        BeanUtils.toBean(list, ActivityRespVO.class));
    }

}